﻿package net.wangit.view.chart.impl;

import net.wangit.MapList;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.chart.util.DatasetUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieToolTipGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.urls.StandardPieURLGenerator;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.PieDataset;


public class PieChart extends AbstractChart {

	private static Log log = LogFactory
			.getLog(net.wangit.view.chart.impl.PieChart.class);

	public PieChart() {
	}

	protected Plot getPlot() {
		PieDataset dataset = (PieDataset) getDataset();
		PiePlot plot = new PiePlot(dataset);
		plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
		configPiePlot(plot);
		return plot;
	}

	protected Dataset toDataset(MapList list) {
		return DatasetUtil.toPieDataset(list);
	}

	protected void configPiePlot(PiePlot plot) {
		if (tooltips)
			plot
					.setToolTipGenerator(Checker.isEmpty(toolTipFormat) ? ((org.jfree.chart.labels.PieToolTipGenerator) (new StandardPieToolTipGenerator()))
							: ((org.jfree.chart.labels.PieToolTipGenerator) (new StandardPieToolTipGenerator(
									toolTipFormat))));
		if (urls)
			plot
					.setURLGenerator(Checker.isEmpty(url) ? ((org.jfree.chart.urls.PieURLGenerator) (new StandardPieURLGenerator()))
							: ((org.jfree.chart.urls.PieURLGenerator) (new StandardPieURLGenerator(
									url))));
		plot.setCircular(pieCircular);
		plot.setSectionOutlinesVisible(pieItemOutlinesVisible);
		plot.setSectionOutlinePaint(itemOutlineColor);
		plot.setSectionOutlineStroke(itemOutlineStroke);
		if (!Checker.isEmpty(itemlabelFormat))
			plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
					itemlabelFormat));
		plot.setLabelLinksVisible(pieLabelLinksVisible);
		plot.setStartAngle(pieStartAngle);
		if (!Checker.isEmpty(pieExplodePercents)) {
			String sections[][] = StringUtil
					.split(pieExplodePercents, ";", ",");
			for (int i = 0; i < sections.length; i++) {
				if (log.isDebugEnabled())
					log.debug((new StringBuilder("i=")).append(
							sections[i][0].trim()).append(" , p=").append(
							sections[i][1].trim()).toString());
				plot.setExplodePercent(Integer.parseInt(sections[i][0].trim()),
						Double.parseDouble(sections[i][1].trim()));
			}

		}
	}

}
